package com.rth.wx.Handler;

import com.rth.common.redis.RedisUtil;
import com.rth.wx.constant.WxConstant;
import com.rth.wx.enums.WechatMsgTypeEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class ReceiveMsgHandler implements WechatMsgHandler {
    @Resource
    private RedisUtil redisUtil;

    @Override
    public WechatMsgTypeEnum getMsgType() {
        return WechatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String handlerByMsgType(Map<String, String> msgMap) {
        String toUserName = msgMap.get("ToUserName");
        String fromUserName = msgMap.get("FromUserName");
        int randomCode = 0;
        if (msgMap.get("Content").equals("验证码")) {
            Random random = new Random();
            randomCode = random.nextInt(9999);

            String vailCode = redisUtil.buildKey(WxConstant.LOGIN_PREFIX,String.valueOf(randomCode));
            redisUtil.setNx(vailCode, fromUserName, 5L, TimeUnit.MINUTES);
            String content = "<xml>\n" +
                    "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                    "  <CreateTime>12345678</CreateTime>\n" +
                    "  <MsgType><![CDATA[text]]></MsgType>\n" +
                    "  <Content><![CDATA[你的验证码为 " + randomCode + " 五分钟内有效！]]></Content>\n" +
                    "</xml>";
            return content;

        }


        String content = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + msgMap.get("Content") + "]]></Content>\n" +
                "</xml>";

        return content;

    }
}
